package com.song.bootstrap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.song.entity.TableDataInfo;
import com.song.entity.user.User;
import com.song.service.user.UserService;
import com.song.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/bootstrap")
public class BootStrapController {

    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public String index() {
        return "bootstrap/manage";
    }

    @RequestMapping("/getData")
    @ResponseBody
    public JSONObject getData(
            @RequestParam(value = "pageNum", defaultValue = "0") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
            String sortOrder, String sortName, String query, String startTime, String endTime) {

        PageHelper.startPage(pageNum, pageSize);
        EntityWrapper<User> ew = new EntityWrapper();
        ew.like("name", query);
        if (StringUtils.isNoneBlank(startTime) && StringUtils.isNoneBlank(endTime)) {
            ew.between("date_format(create_time,'%Y-%m-%d')", startTime, endTime);
        }
        ew.orderBy(sortName, "asc".equals(sortOrder));
        List<User> list = userService.selectList(ew);

        PageInfo<User> pageInfo = new PageInfo<>(list);

        JSONObject obj = new JSONObject();
        obj.put("total", (int) pageInfo.getTotal());

        JSONArray array = new JSONArray();
        for (User user : list) {
            JSONObject json = new JSONObject();
            json.put("id", user.getId());
            json.put("name", user.getName());
            json.put("account", user.getAccount());
            json.put("age", user.getAge());
            json.put("time", DateUtils.formatDate(user.getCreateTime(), "yyyy-MM-dd"));
            array.add(json);
        }
        obj.put("rows", array);
        return obj;
    }
}
